package com.msb.test17;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;

public class DOMParserExample {
    public static void main(String[] args) {
        try {
            File inputFile = new File("TestFirstModule/src/student.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("student"); // 替换为实际的节点名称

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;

                    // 获取属性值
                    String attribute = eElement.getAttribute("attributeName"); // 替换为实际的属性名称
                    System.out.println("Attribute : " + attribute);

                    // 获取子节点值
                    String value = eElement.getElementsByTagName("childNodeName").item(0).getTextContent(); // 替换为实际的子节点名称
                    System.out.println("Value : " + value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}